<template>
  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-input v-model="listQuery.username" placeholder="用户名称" />
      <el-date-picker
        v-model="daterangeValue"
        :picker-options="daterangePickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建起始时间"
        end-placeholder="创建结束时间"
        value-format="yyyy-MM-dd"
        @change="daterangeChanged"
      />
      <el-button type="primary" @click="handleFilter">查询</el-button>
      <el-button type="warning" @click="resetFilter">重置</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="handleAdd"
        >添加</el-button
      >
    </div>

    <div class="cs-filter-result">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        size="small"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column align="center" label="内部ID">
          <template slot-scope="scope">
            <span>{{ scope.row.uid }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="用户名称">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="角色名称">
          <template slot-scope="scope">
            <template v-for="role in scope.row.roles">{{
              role.roleName
            }}</template>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间" min-width="150">
          <template slot-scope="scope">
            <span>{{
              scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}')
            }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="更新时间" min-width="150">
          <template slot-scope="scope">
            <span>{{
              scope.row.updatedAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}')
            }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" min-width="160">
          <template slot-scope="{ row }">
            <el-button size="mini" type="primary" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
            <el-button size="mini" type="warning" @click="handleRestPwd(row)"
              >密码重置</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <TablePagination
        :current-page="listQuery.page"
        :limit="listQuery.limit"
        :total="total"
        :loading="listLoading"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>

    <el-dialog :title="operationFormTitle" :visible.sync="operationFormVisible">
      <el-form
        ref="operationInfo"
        :rules="rules"
        class="small-space"
        :model="operationInfo"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input
            v-model="operationInfo.username"
            :disabled="operationInfo.type == 'modify'"
          />
        </el-form-item>

        <el-form-item label="用户角色" prop="roleId">
          <el-select
            v-model="operationInfo.roleId"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.text"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="operationFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TablePagination from '@components/TablePagination'

import {
  xhrGetRoleOptions,
  xhrGetAccountList,
  xhrDelAccount,
  xhrResetAccoutPwd,
  xhrAddAccount,
  xhrEditAccount
} from '@api/system'

export default {
  name: 'SystemAccountList',
  components: { TablePagination },
  data() {
    return {
      list: null,
      total: 0,
      daterangeValue: '',
      listQuery: {
        offset: 0,
        limit: 10,
        page: 1,
        username: null,
        startTime: null,
        endTime: null
      },
      operationFormTitle: '',
      operationFormVisible: false,
      operationInfo: {},
      addFormVisible: false,
      roleOptions: [],
      rules: {
        username: [{ required: true, message: '不能为空', trigger: 'change' }],
        roleId: [{ required: true, message: '不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.doSearch()
    this.getRoleListConfig()
  },
  methods: {
    daterangeChanged() {
      this.listQuery.startTime =
        (this.daterangeValue &&
          this.daterangeValue[0] &&
          this.daterangeValue[0]) ||
        null
      this.listQuery.endTime =
        (this.daterangeValue &&
          this.daterangeValue[1] &&
          this.daterangeValue[1] + ' 23:59:59') ||
        null
    },
    doSearch() {
      this.listLoading = true
      this.listQuery.offset = (this.listQuery.page - 1) * this.listQuery.limit
      xhrGetAccountList(this.listQuery)
        .then(resp => {
          this.list = resp.data.items
          this.total = resp.data.count
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getRoleListConfig() {
      xhrGetRoleOptions().then(resp => {
        this.roleOptions = resp.data.items
      })
    },
    handleAdd() {
      this.operationFormVisible = true
      this.operationFormTitle = '新增账号'
      this.operationInfo = {
        type: 'add',
        username: '',
        role: ''
      }
      this.$nextTick(() => {
        this.$refs['operationInfo'].clearValidate()
      })
    },
    handleEdit(row) {
      this.operationFormVisible = true
      this.operationFormTitle = '编辑'
      this.operationInfo = {
        type: 'modify',
        uid: row.uid,
        username: row.username,
        roleId: row.roles.length > 0 ? row.roles[0].id : ''
      }
    },
    handleDelete(row) {
      this.$confirm(`确认删除此账号？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        xhrDelAccount({ uid: row.uid }).then(resp => {
          if (resp.code === 0) {
            this.doSearch()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: resp.msg,
              type: 'error'
            })
          }
        })
      })
    },
    handleRestPwd(row) {
      this.$confirm(`确认重置密码？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        xhrResetAccoutPwd({ uid: row.uid }).then(resp => {
          if (resp.code === 0) {
            this.doSearch()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: resp.msg,
              type: 'error'
            })
          }
        })
      })
    },
    confirm() {
      this.$refs['operationInfo'].validate(valid => {
        if (valid) {
          const params = {
            roleId: this.operationInfo.roleId,
            channelIdList: []
          }
          if (this.operationInfo.type === 'add') {
            params.username = this.operationInfo.username
            xhrAddAccount(params).then(resp => {
              if (resp.code === 0) {
                this.doSearch()
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.operationFormVisible = false
              } else {
                this.$message({
                  message: resp.msg,
                  type: 'error'
                })
              }
            })
          }
          if (this.operationInfo.type === 'modify') {
            params.uid = this.operationInfo.uid
            xhrEditAccount(params).then(resp => {
              if (resp.code === 0) {
                this.doSearch()
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.operationFormVisible = false
              } else {
                this.$message({
                  message: resp.msg,
                  type: 'error'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
